//
//  XMTabBarController.m
//  XMWeibo
//
//  Created by chi on 14-8-19.
//  Copyright (c) 2014年 xiaoming. All rights reserved.
//

#import "XMTabBarController.h"
#import "XMHomeController.h"
#import "XMTabBar.h"
#import "XMMessageController.h"
#import "XMDiscoverController.h"
#import "XMMeController.h"
#import "XMNavigationController.h"
#import "SoundTool.h"

#import "XMWeiboAccount.h"

#import "MJExtension.h"

#import "XMLoadUserInfoTool.h"

#import "XMSendStatusController.h"


@interface XMTabBarController () <XMTabBarDelegate>

/** 自定义tabbar */
@property (nonatomic ,weak) XMTabBar *customTabBar;

/** home控制器 */
@property (nonatomic,weak) XMHomeController *home;

/** msg控制器 */
@property (nonatomic, weak) XMMessageController *msg;

/** discover控制器 */
@property (nonatomic, weak) XMDiscoverController *discover;

/** me控件器 */
@property (nonatomic, weak) XMMeController *me;

/** 播放器 */
@property (nonatomic, strong) SoundTool *soundTool;

@end

@implementation XMTabBarController



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //创建自定义tabar
    [self setupCustomeTabBar];

    //创建tabbar子视图
    [self setupTabbarChildControllers];
    
    //创建定时器检测用户未读消息
    NSTimer *timer = [NSTimer timerWithTimeInterval:20.0f target:self selector:@selector(check_remind_unread_count:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];

    // 在后台加载音乐资源
    [self loadAudioInBackground];
    
    
}

- (void)setMyBadgeValue
{
    if (self.me.tabBarItem.badgeValue == nil) {
        self.me.tabBarItem.badgeValue = @"new";
        self.discover.tabBarItem.badgeValue = @"99+";
    }
}

/**
 *  在后台加载音乐资源
 */
- (void)loadAudioInBackground
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [[SoundTool sharedSoundTool] playBackgroundMusic];
    });
}

/**
 *  定时检查新消息
 */
- (void)check_remind_unread_count:(NSTimer *)timer
{
    
    

    XMHttpLoadUserInfoParams *params = [XMHttpLoadUserInfoParams params];
    params.uid = @([XMWeiboAccount account].uid);
    
    [XMLoadUserInfoTool httpLoadUserUnreadCountWithParams:params success:^(XMHttpLoadUnreadCountResult *result) {
        if (result.status < 1) {
            self.home.tabBarItem.badgeValue = @"";
        }
        else {
            if (result.status > 99) {
                self.home.tabBarItem.badgeValue = @"99+";
            }
            else {
                self.home.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d", result.status ];
            }
        }
        
        if (result.msgCount < 1) {
            self.msg.tabBarItem.badgeValue = @"";
        }
        else {
            if (result.msgCount > 99) {
                self.msg.tabBarItem.badgeValue = @"99+";
            }
            else {
                self.msg.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d", result.msgCount ];
            }
        }
        
        
        [UIApplication sharedApplication].applicationIconBadgeNumber = result.count;
        
    } failure:^(NSError *error) {
        XMLog(@"%@请求失败，失败原因: %@", k_remind_unread_count, error);
    }];
    
}

/**
 *  创建tab子控件器
 */
- (void)setupTabbarChildControllers
{
    //主页
    XMHomeController *home = [[XMHomeController alloc]init];
    self.home = home;
   [self addController:home withTitle:@"首页" andNormalImage:@"tabbar_home" andSelectedImage:@"tabbar_home_selected"];
    
    //消息
    XMMessageController *msg = [[XMMessageController alloc]init];
    self.msg = msg;
    [self addController:msg withTitle:@"消息" andNormalImage:@"tabbar_message_center" andSelectedImage:@"tabbar_message_center_selected" ];
    
    //发现
    XMDiscoverController *discover = [[XMDiscoverController alloc]init];
    [self addController:discover withTitle:@"发现" andNormalImage:@"tabbar_discover" andSelectedImage:@"tabbar_discover_selected"];
    self.discover = discover;
    
    //我
    XMMeController *me = [[XMMeController alloc]init];
    [self addController:me withTitle:@"我" andNormalImage:@"tabbar_profile" andSelectedImage:@"tabbar_profile_selected"];
    self.me = me;
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    

    //移除系统自带的UITabBarButton
    Class cla = NSClassFromString(@"UITabBarButton");
    for (id view in self.tabBar.subviews) {
        if ([view isKindOfClass:cla]) {
            [view removeFromSuperview];
        }
    }
    
    
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.me.tabBarItem.badgeValue = @"new";
    self.discover.tabBarItem.badgeValue = @"99+";
}


/**
 *  新建微博按钮
 */
- (void)clickNewWeibboButton
{

    XMSendStatusController *sendVc = [[XMSendStatusController alloc]init];
    XMNavigationController *nav = [[XMNavigationController alloc]initWithRootViewController:sendVc];
    
    
    [self presentViewController:nav animated:YES completion:nil];
}

/**
 *  切换tab
 */
- (void)selectTabBarFrom:(NSUInteger)from To:(NSUInteger)to
{
    self.selectedIndex = to;
    if (to == 0) {
        // 有更新数量时才刷新
        if ([self.home.tabBarItem.badgeValue intValue] > 0) {
            [self.home headerBeginRefreshing];
        }
    }
}

/**
 *  创建自定义tabbar
 */
- (void)setupCustomeTabBar
{
    XMTabBar *customeTabBar = [[XMTabBar alloc]initWithFrame:self.tabBar.bounds];
    customeTabBar.delegate = self;
    
    [self.tabBar addSubview:customeTabBar];
    
    self.customTabBar = customeTabBar;

}

/**
 *  添加tab control
 */
- (void)addController:(UIViewController*)childVc withTitle:(NSString*)title andNormalImage:(NSString*)normal andSelectedImage:(NSString*)selected
{

    childVc.title = title;
    childVc.tabBarItem.image = [UIImage adaptIOS7ImageWithName:normal];
    
    if (isIOS7) {
         childVc.tabBarItem.selectedImage = [UIImage adaptIOS7ImageWithName:selected];
    }
    else {
        childVc.tabBarItem.selectedImage = [UIImage adaptIOS7ImageWithName:selected];
    }
   
    
    XMNavigationController *nav = [[XMNavigationController alloc]initWithRootViewController:childVc];
    
    
    [self.customTabBar addTabBarButtonWithItem:childVc.tabBarItem];
    
    [self addChildViewController:nav];
    
}

@end
